import pystray
from PIL import Image, ImageDraw
import os
import platform
import logging
from ws.ws_client import run_async_websocket
from com_utils import run_in_thread

logger = logging.getLogger("VoiceAssistant")

def create_tray_icon():
    def create_image():
        """创建托盘图标图像"""
        width, height = 64, 64
        image = Image.new('RGB', (width, height), (40, 40, 40))
        dc = ImageDraw.Draw(image)
        dc.ellipse((15, 15, 50, 50), fill=(0, 200, 0))
        dc.rectangle((32, 10, 34, 25), fill="white")
        dc.rectangle((20, 45, 45, 48), fill="white")
        return image
        
    def exit_app():
        """退出应用程序"""
        tray_icon.stop()  # 使用参数icon代替全局变量tray_icon
        os._exit(0)
    
    def restart_connection():
        """重启WebSocket连接"""
        run_in_thread(run_async_websocket)
        
    def open_log_file():
        """打开日志文件"""
        try:
            if platform.system() == "Windows":
                os.startfile("voice_assistant.log")
            elif platform.system() == "Darwin":
                os.system("open voice_assistant.log")
            else:  # Linux
                os.system("xdg-open voice_assistant.log")
        except Exception as e:
            logger.error(f"无法打开日志文件: {str(e)}")
    
    # 修改菜单项回调函数以接收icon参数
    menu_items = [
        pystray.MenuItem('打开日志文件', lambda: open_log_file()),
        pystray.MenuItem('重启连接', lambda: restart_connection()),
        pystray.MenuItem('退出', exit_app),  # 直接传递exit_app函数
    ]
    
    # 创建菜单对象
    menu = pystray.Menu(*menu_items)
    
    image = create_image()
    # 创建并返回图标对象
    tray_icon = pystray.Icon("voice_assistant", image, "语音助手", menu)
    return tray_icon